import java.util.*;

public class SpamHandler
{
	LinkedList<String> targets = new LinkedList<String>();
	HashMap<String, Long> next_time = new HashMap<String, Long>();
	HashMap<String, Long> delay = new HashMap<String, Long>();

	long delay_time = 0;

	public SpamHandler()
	{
		delay.put("top", 60000l);
		delay.put("stats", 60000l);
		delay.put("lobby", 60000l);
		delay.put("vent", 60000l);
		delay.put("stream", 60000l);

		next_time.put("top", 0l);
		next_time.put("lobby", 0l);
		next_time.put("vent", 0l);
	}

	public boolean allowCmd(String cmd)
	{
		DataManager dm = DataManager.getInstance();
		// Mods and PMs are always fine
		if (dm != null && dm.isMod(LeagueBot.name) && LeagueBot.target.equalsIgnoreCase(LeagueBot.botname))
			return true;

		// Only delay specified commands
		if (!delay.containsKey(cmd))
			return true;

		// Handling for commands that don't have an additional key
		if (!cmd.equals("stats") && !cmd.equals("stream"))
		{
			if (next_time.get(cmd) < System.currentTimeMillis())
			{
				next_time.put(cmd, System.currentTimeMillis() + delay.get(cmd));
				return true;
			}
			else
			{
				return false;
			}
		}

		// !stats and !stream specific
		String key = LeagueBot.text.trim().toLowerCase();
		if (next_time.containsKey(key))
		{
			if (next_time.get(key) < System.currentTimeMillis())
			{
				next_time.put(key, System.currentTimeMillis() + delay.get(cmd));
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			next_time.put(key, System.currentTimeMillis() + delay.get(cmd));
			return true;
		}
	}

	public long getDelay(String target)
	{
		if (targets.contains(target))
		{
			targets.remove(target);
			targets.addFirst(target);
			return 0;
		}

		long cur_time = System.currentTimeMillis();
		DataManager dm = DataManager.getInstance();
		if (dm != null && !dm.isMod(target) && delay_time > cur_time)
		{
			return delay_time - cur_time;
		}

		// Only save 17 general slots (keep 2 for admins, 1 for hosts)
		if (cur_time - delay_time > 15000 * 17)
			delay_time = cur_time - 15000 * 17;

		delay_time += 15000;

		if (targets.size() == 20)
			targets.removeLast();

		targets.addFirst(target);

		return 0;
	}
}
